var current;

function getDate( d, sparator ){
	if( d === undefined || d == null ) {
		d = new Date();
	}
	var year = d.getFullYear();
	var month = d.getMonth() + 1 + '';
	if( month.length == 1 ) {
		month = "0" + month;
	}
	var date = d.getDate() + '';
	if( date.length == 1 ) {
		date = "0" + date;
	}
	
	if( sparator === undefined || sparator == null ) {
		return year + '年' + month + '月' + date + '日';	
	} else {
		return year + sparator + month + sparator + date;
	}
}

function getTime12Hours( d, sparator ) {
	if( d === undefined || d == null ) {
		d = new Date();
	}
	var hour = d.getHours();
	if( hour > 12 ) {
		hour -= 12;
	}
	hour += '';
	if( hour.length == 1 ) {
		hour = "0" + hour;
	}
	var minute = d.getMinutes() + '';
	if( minute.length == 1 ) {
		minute = "0" + minute;
	}
	var second = d.getSeconds() + '';
	if( second.length == 1 ) {
		second = "0" + second;
	}
	
	if( sparator === undefined || sparator == null ) {
		if( d.getHours() < 12 ) {   
			return '上午' + hour + '时' + minute + '分';	
		} else {
			return '下午' + hour + '时' + minute + '分';	
		}
	} else {
		if( d.getHours() < 12 ) {   
			return '上午' + hour + sparator + minute;	
		} else {
			return '下午' + hour + sparator + minute;	
		}
	}
}

function getTime( d, sparator ){
	if( d === undefined || d == null ) {
		d = new Date();
	}
	var hour = d.getHours() + '';
	if( hour.length == 1 ) {
		hour = "0" + hour;
	}
	var minute = d.getMinutes() + '';
	if( minute.length == 1 ) {
		minute = "0" + minute;
	}
	var second = d.getSeconds() + '';
	if( second.length == 1 ) {
		second = "0" + second;
	}
	
	if( sparator === undefined || sparator == null ) {
		return hour + '时' + minute + '分';	
	} else {
		return hour + sparator + minute;
	}
}

function getWeekday( d ){
	if( d === undefined || d == null ) {
		d = new Date();
	}
	
	if( d.getDay() == 0 ) {
		return '星期日'; 
	} else if( d.getDay() == 1 ) {
		return '星期一'; 
	} else if( d.getDay() == 2 ) {
		return '星期二'; 
	} else if( d.getDay() == 3 ) {
		return '星期三'; 
	} else if( d.getDay() == 4 ) {
		return '星期四'; 
	} else if( d.getDay() == 5 ) {
		return '星期五'; 
	} else if( d.getDay() == 6 ) {
		return '星期六'; 
	}
}

function dayStart( d ){
	if( d === undefined || d == null ) {
		d = new Date();
	}
	return new Date( d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0 );
}

function dayEnd( d ){
	if( d === undefined || d == null ) {
		d = new Date();
	}
	return new Date( d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59 );
}

function timestamp( d ){
	var t = d.getTime();
	return t / 1000;
}

var startMessage;
var stopRefresh = false;
var userArr = {};

function refreshMessage( base_url, messages ) {
	var args = loadArguments();
	if( messages.length > 0 ) {
		var $hr = $( '<div class="hr ui-corner-all">' + getTime() + '</div>' );
		$( '#messages' ).append( $hr );
	}
	
	for( var i = 0; i < messages.length; i++ ) {
		var msg = messages[ messages.length - 1 - i ].WechatMessage;
		
		var $msg = $( '<div class="wechat-message ui-body ui-body-a ui-corner-all"></div>' );
		if( userArr[msg.from_username] !== undefined && userArr[msg.from_username] != null ) {
			var $header = $( '<div class="ui-grid-a ' + msg.from_username + '"></div>' );
			$header.append( $( '<div class="ui-block-a"><h1 class="' + msg.from_username + '"><img src="' + userArr[msg.from_username].headimgurl + '" /><strong>' + userArr[msg.from_username].nickname + '</strong></h1></div>' ) );
			if( args.admin ) {
				if( msg.status == 'REVIEWED' ) {
					$header.append( $( '<div class="ui-block-b"><select name="' + msg.id + '" data-role="slider" data-mini="true"><option value="off">关</option><option value="on" selected="">开</option></select></span></div>' ) );
				} else {
					$header.append( $( '<div class="ui-block-b"><select name="' + msg.id + '" data-role="slider" data-mini="true" data-inline="true"><option value="off" selected="">关</option><option value="on">开</option></select></span></div>' ) );
				}
			}
			
			$msg.append( $header );
		} else {
			var $header = $( '<div class="ui-grid-a ' + msg.from_username + '"></div>' );
			$header.append( $( '<div class="ui-block-a"><h1></h1></div>' ) );
			if( args.admin ) {
				if( msg.status == 'REVIEWED' ) {
					$header.append( $( '<div class="ui-block-b"><select name="' + msg.id + '" data-role="slider" data-mini="true"><option value="off">关</option><option value="on" selected="">开</option></select></span></div>' ) );
				} else {
					$header.append( $( '<div class="ui-block-b"><select name="' + msg.id + '" data-role="slider" data-mini="true" data-inline="true"><option value="off" selected="">关</option><option value="on">开</option></select></span></div>' ) );
				}
			}
			$msg.append( $header );
			
			$.get( base_url + "/restapi/wechat/get/APIGetWechatAccount", { openid : msg.from_username }, function( data ){
				if( data.status == 200 ) {
					if( data.result.nickname !== undefined && data.result.nickname != null ) {
						userArr[data.result.openid] = data.result;
						$( '.' + data.result.openid ).each(function(index, element) {
                            var $this = $( this );
							if( !$( 'h1', $this ).hasClass( data.result.openid ) ) 
								$( 'h1', $this ).addClass( data.result.openid );
							$( 'h1', $this ).html( '<img src="' + userArr[data.result.openid].headimgurl + '" /><strong>' + userArr[data.result.openid].nickname + '</strong>' );
                        });
					}
				} else {
					
				}
			});
		}
		
		if( msg.content.msg_type == 'text' ) {
			$msg.append( $( '<p>' + msg.content.text + '</p>' ) );
		} else if( msg.content.msg_type == 'image' ) {
			var img = JSON.parse( msg.content.image );
			var imageUrl = args.base_url + '/restapi/files/WankImage?filename=' + img.media_id;
			$msg.append( $( '<img src="' + imageUrl + '" />' ) );
		}
			
		$( '#messages' ).append( $msg );
		startMessage = msg.id;
	}
	
	$( 'select', '#messages' ).each(function(index, element) {
		$( this ).change(function(e) {
			var status = "NOT_REVIEW";
			if( $( this ).val() == 'on' ){
				status = "REVIEWED";
			} else {
				status = "BANNED";
			}
			var url = args.base_url + "/restapi/wechat/edit/APIEditMessage";
			var params = {
				id : $( this ).attr( "name" ),
				status : status,
			};
			$.post( url, params );
		});
    });
	
	$("html, body").animate({ scrollTop: $(document).height() }, "slow");
}

function getMessageTime( t ){
	// 2014-03-31 00:00
	var date = t.substring(0,10);
	var time = t.substring(11,16);
	var d = new Date( date + 'T' + time );
	d = new Date( d.getTime() - 8 * 60 * 60 * 1000 );
	
	var result = '';
	
	if( d.getHours() < 12 ) {
		result = '上午<strong>' + getTime12Hours( d, ":" ).substring(2,7) + '</strong>';
	} else {
		result = '下午<strong>' + getTime12Hours( d, ":" ).substring(2,7) + '</strong>';
	}
	return result;
}

function loadMessages(){
	var args = loadArguments();
	var url = args.base_url + "/restapi/wechat/list/APIListMessage";
	var status = 'REVIEWED';
	if( args.admin ){
		status = 'ALL_STATUS';
	}
	var params = { 
		start_time : timestamp( dayStart() ),
		end_time : timestamp( dayEnd() ),
		to_account : args.to_account,
		message_types : 'text,voice,news,image',
		start_pos : 0,
		offset : 10,
		order_by : 'create_time',
		sort : 'desc',
		status : status,
		start_message : startMessage,
	};
	
	$.post( url, params, function( data ){
		if( data.status == 200 ) {
			refreshMessage( args.base_url, data.result.list );
			$( '.wank-wechatmessage' ).trigger( "create" );
		} else {
			alert( data.message );
		}
		if( !stopRefresh ) setTimeout( loadMessages, 3000 );
	});
}

$( document ).on( 'pagecreate', '.wank-wechatmessage', function( event ) {
	localStorage.clear();
	loadMessages();
});

$( document ).on( "pageinit", ".wank-wechatmessage", function( event ) {
	
});
